package com.jml.netty.version5;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

public class NettyServer {

	public static void main(String[] args) throws Exception {
		System.out.println("服务器端已经启动....");
		// 1.创建2个线程,一个负责接收客户端连接， 一个负责进行 传输数据
		NioEventLoopGroup pGroup = new NioEventLoopGroup();
		NioEventLoopGroup cGroup = new NioEventLoopGroup();
		// 2. 创建服务器辅助类
		ServerBootstrap serverBootstrap = new ServerBootstrap();
		serverBootstrap.group(pGroup, cGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 1024)
				// 3.设置缓冲区与发送区大小  大小一致
				.option(ChannelOption.SO_SNDBUF, 32 * 1024).option(ChannelOption.SO_RCVBUF, 32 * 1024)
				.childHandler(new ChannelInitializer<SocketChannel>() {
					@Override
					protected void initChannel(SocketChannel sc) throws Exception {

						//定长10个字符
						//sc.pipeline().addLast(new FixedLengthFrameDecoder(10));

						//分隔符为_mayi
						ByteBuf buf = Unpooled.copiedBuffer("_mayi".getBytes());
						sc.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, buf));

						//接收参数是String类型的
						sc.pipeline().addLast(new StringDecoder());
						sc.pipeline().addLast(new ServerHandler());
					}
				});
		ChannelFuture channelFuture = serverBootstrap.bind(8080).sync();
		channelFuture.channel().closeFuture().sync();
		pGroup.shutdownGracefully();
		cGroup.shutdownGracefully();

	}


}
